<template>
  <el-form :inline="true" :model="queryForm" class="demo-form-inline">
    <el-form-item label="用户组名:">
      <el-input
        v-model="queryForm.name"
        placeholder="请输入用户组名"
        clearable
        style="width: 200px"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="querySubmit">查询</el-button>
    </el-form-item>
  </el-form>

  <div class="table-header">
    <span class="table-title">用户组列表</span>
    <el-button type="primary" @click="addGroupDialog = true">添加</el-button>
  </div>
  <el-table :data="tableData">
    <el-table-column prop="name" label="用户组名" />
    <el-table-column prop="desc" label="描述" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button link type="primary" size="small" @click="openBindUserDialog(row.id)">
          管理成员</el-button
        >
        <el-button link type="primary" size="small" @click="openBindRoleDialog(row.id)">
          管理角色</el-button
        >
        <el-button link type="primary" size="small" @click="openUpdateGroupDialog(row)">
          编辑</el-button
        >
        <el-button link type="danger" size="small" @click="fetchDeleteGroup(row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-container">
    <el-pagination
      v-if="page.total > 0"
      v-model:current-page="pageNumber"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40, 50]"
      :size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog v-model="addGroupDialog" title="添加用户组" width="500">
    <el-form :model="addGroupForm">
      <el-form-item label="用户组名" :label-width="formLabelWidth">
        <el-input v-model="addGroupForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" :label-width="formLabelWidth">
        <el-input v-model="addGroupForm.desc" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addGroupDialog = false">取消</el-button>
        <el-button type="primary" @click="fetchAddGroup"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="updateGroupDialog" title="更新用户组" width="500">
    <el-form :model="updateGroupForm">
      <el-form-item label="用户组名" :label-width="formLabelWidth">
        <el-input v-model="updateGroupForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="desc" :label-width="formLabelWidth">
        <el-input v-model="updateGroupForm.desc" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateGroupDialog = false">取消</el-button>
        <el-button type="primary" @click="fetchUpdateGroup(updateGroupForm.id)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加/移除成员 -->
  <el-dialog v-model="bindUserDialog" width="70%">
    <el-form :inline="true" :model="memberqueryForm" class="demo-form-inline">
      <el-form-item label="用户名:">
        <el-input
          v-model="memberqueryForm.username"
          placeholder="请输入用户名"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="邮箱:">
        <el-input
          v-model="memberqueryForm.email"
          placeholder="请输入邮箱"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="memberquerySubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <span class="table-title">用户列表</span>
      <el-button type="primary" @click="addUserDialog()">绑定</el-button>
    </div>
    <el-table :data="bindUserList">
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button link type="danger" @click="fetchUbindUser([row.id])" circle>解绑</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <el-dialog v-model="bindUserListDialog" width="35%" title="绑定用户">
    <el-select v-model="bindUserId" multiple clearable placeholder="请选择用户">
      <el-option
        v-for="item in optionsUserList"
        :key="item.id"
        :label="`${item.username} (${item.email})`"
        :value="item.id"
      />
    </el-select>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="bindUserListDialog = false">取消</el-button>
        <el-button type="primary" @click="bindUserSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="bindRoleDialog" width="70%">
    <el-form :inline="true" :model="rolequeryForm" class="demo-form-inline">
      <el-form-item label="角色名:">
        <el-input
          v-model="rolequeryForm.name"
          placeholder="请输入角色名"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="rolequerySubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <span class="table-title">角色列表</span>
      <el-button type="primary" @click="addRoleDialog()">绑定</el-button>
    </div>
    <el-table :data="bindRoleList">
      <el-table-column prop="name" label="角色名" />
      <el-table-column prop="desc" label="描述" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button link type="danger" @click="fetchUbindRole([row.id])" circle>解绑</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <el-dialog v-model="bindRoleListDialog" width="35%" title="绑定角色">
    <el-select v-model="bindRoleId" multiple clearable placeholder="请选择角色">
      <el-option
        v-for="item in optionsRoleList"
        :key="item.id"
        :label="`${item.name}`"
        :value="item.id"
      />
    </el-select>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="bindRoleListDialog = false">取消</el-button>
        <el-button type="primary" @click="bindRoleSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
  
  <script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue'
import {
  listGroup,
  createGroup,
  deleteGroup,
  updateGroup,
  bindUser,
  bindRole,
  listBindUser,
  listBindRole
} from '@/api/group'
import { listUser } from '@/api/user'
import { ElMessage } from 'element-plus'
import { listRole } from '@/api/role'

const addGroupDialog = ref(false)
const updateGroupDialog = ref(false)
const formLabelWidth = '140px'
const page = reactive({ total: 0 })
const pageSize = ref(10)
const pageNumber = ref(1)

const initAddGroupForm = reactive({
  name: '',
  desc: ''
  // 添加其他字段
})

const addGroupForm = reactive({ ...initAddGroupForm })
const updateGroupForm = reactive({ ...initAddGroupForm })
const queryForm = reactive({ ...initAddGroupForm })

const tableData = ref([])
const bindUserDialog = ref(false) //用户组成员列表弹框
const bindUserListDialog = ref(false) //可选用户列表弹框
const optionsUserList = ref([]) //添加成员时，列出可选成员
const bindUserList = ref([]) //绑定成员列表
const bindUserId = ref()
const curGroupId = ref() //当前用户组id
const memberqueryForm = reactive({
  username: '',
  email: ''
})

const bindRoleDialog = ref(false)
const bindRoleListDialog = ref(false)
const optionsRoleList = ref([])
const bindRoleList = ref([])
const bindRoleId = ref()
const rolequeryForm = reactive({
  name: ''
})

//管理成员
const openBindUserDialog = (id: number) => {
  bindUserDialog.value = true
  curGroupId.value = id
  fetchBindUserList(curGroupId.value, {})
}

const fetchBindUserList = async (id: number, query: {}) => {
  try {
    const resp = await listBindUser(id, query)
    if (resp.status < 300) {
      bindUserList.value = resp.data.data
    }
  } catch (error) {}
}

const memberquerySubmit = async () => {
  try {
    const resp = await listBindUser(curGroupId.value, {
      username: memberqueryForm.username,
      email: memberqueryForm.email
    })
    if (resp.status < 300) {
      bindUserList.value = resp.data.data
    }
  } catch (error) {}
}

const addUserDialog = async () => {
  bindUserListDialog.value = true
  bindUserId.value = null

  try {
    const resp = await listUser({ page: 1, size: 100 })
    optionsUserList.value = resp.data.data
  } catch (error) {
    console.log(error)
  }
}

const bindUserSubmit = async () => {
  try {
    const data = { group_id: curGroupId.value, user_ids: bindUserId.value, action: 'bind' }
    const resp = await bindUser(data)
    if (resp.status < 300) {
      bindUserListDialog.value = false
      ElMessage.success('绑定成功')
      fetchBindUserList(curGroupId.value, {
        username: memberqueryForm.username,
        email: memberqueryForm.email
      })
    }
  } catch (error) {
    console.log(error)
  }
}

const fetchUbindUser = async (id: number) => {
  try {
    const data = { group_id: curGroupId.value, user_ids: id, action: 'ubind' }
    const resp = await bindUser(data)
    if (resp.status < 300) {
      bindUserListDialog.value = false
      ElMessage.success('解绑成功')
      fetchBindUserList(curGroupId.value, {
        username: memberqueryForm.username,
        email: memberqueryForm.email
      })
    }
  } catch (error) {
    console.log(error)
  }
}

//管理角色
const openBindRoleDialog = (id: number) => {
  bindRoleDialog.value = true
  curGroupId.value = id
  fetchBindRoleList(curGroupId.value, {})
}

const fetchBindRoleList = async (id: number, query: {}) => {
  try {
    const resp = await listBindRole(id, query)
    if (resp.status < 300) {
      bindRoleList.value = resp.data.data
    }
  } catch (error) {}
}

const rolequerySubmit = async () => {
  try {
    const resp = await listBindRole(curGroupId.value, {
      name: rolequeryForm.name
    })
    if (resp.status < 300) {
      bindRoleList.value = resp.data.data
    }
  } catch (error) {}
}

const addRoleDialog = async () => {
  bindRoleListDialog.value = true
  bindRoleId.value = null

  try {
    const resp = await listRole({ page: 1, size: 100 })
    optionsRoleList.value = resp.data.data
  } catch (error) {
    console.log(error)
  }
}

const bindRoleSubmit = async () => {
  try {
    const data = { group_id: curGroupId.value, role_ids: bindRoleId.value, action: 'bind' }
    const resp = await bindRole(data)
    if (resp.status < 300) {
      bindRoleListDialog.value = false
      ElMessage.success('绑定成功')
      fetchBindRoleList(curGroupId.value, { name: rolequeryForm.name })
    }
  } catch (error) {
    console.log(error)
  }
}

const fetchUbindRole = async (id: number) => {
  try {
    const data = { group_id: curGroupId.value, role_ids: id, action: 'ubind' }
    const resp = await bindRole(data)
    if (resp.status < 300) {
      bindRoleListDialog.value = false
      ElMessage.success('解绑成功')
      fetchBindRoleList(curGroupId.value, { name: rolequeryForm.name })
    }
  } catch (error) {
    console.log(error)
  }
}

// 定义一个方法来获取用户组列表
const fetchListGroup = async (params: {}) => {
  try {
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([key, value]) => value !== undefined && value !== '')
    )
    const res = await listGroup(filteredParams)
    tableData.value = res.data.data
    page.total = res.data.total
  } catch (error) {
    console.error('Failed to fetch user list:', error)
  }
}

const querySubmit = () => {
  pageNumber.value = 1
  fetchListGroup({
    page: pageNumber.value,
    size: pageSize.value,
    name: queryForm.name
  })
}

const openUpdateGroupDialog = (row: any) => {
  // Object.assign(updateUserForm, row)
  updateGroupForm.name = row.name
  updateGroupForm.desc = row.desc
  updateGroupForm.id = row.id // 需要确保 uuid 存在
  updateGroupDialog.value = true
}

const fetchAddGroup = async () => {
  try {
    const res = await createGroup(addGroupForm)
    if (res.status < 300) {
      ElMessage.success('添加用户组成功')
      addGroupDialog.value = false
      Object.assign(addGroupForm, initAddGroupForm) //重置表单内容，不然会显示上次的内容
      // 提交成功后刷新用户列表
      pageNumber.value = 1
      fetchListGroup({
        page: pageNumber.value,
        size: pageSize.value,
        name: queryForm.name
      })
    } else {
      ElMessage.error('添加用户组失败')
    }
  } catch (error) {
    ElMessage.error('添加用户组失败')
    console.error('Failed to add user:', error)
  }
}
// 定义一个方法来更新用户
const fetchUpdateGroup = async (uuid: string) => {
  try {
    const res = await updateGroup(uuid, updateGroupForm)
    if (res.status < 300) {
      ElMessage.success('更新用户组成功')
      // 提交成功后刷新用户组列表
      updateGroupDialog.value = false
      pageNumber.value = 1
      fetchListGroup({
        page: pageNumber.value,
        size: pageSize.value,
        name: queryForm.name
      })
    } else {
      ElMessage.error('更新用户组失败')
    }
  } catch (error) {
    console.error('Failed to update user:', error)
  }
}

// 定义一个方法来删除用户组
const fetchDeleteGroup = async (id: string) => {
  try {
    const res = await deleteGroup(id)
    if (res.status < 300) {
      ElMessage.success('删除用户组成功')
      // 提交成功后刷新用户组列表
      pageNumber.value = 1
      fetchListGroup({
        page: pageNumber.value,
        size: pageSize.value,
        name: queryForm.name
      })
    } else {
      ElMessage.error('删除用户组失败')
    }
  } catch (error) {
    ElMessage.error('删除用户组失败')
    console.error('Failed to delete user:', error)
  }
}

// 使用 onMounted 在组件挂载后调用 fetchUserList 方法
onMounted(() => {
  fetchListGroup({ page: pageNumber.value, size: pageSize.value })
})

const handleSizeChange = (size: number) => {
  pageSize.value = size
  pageNumber.value = 1 // 重置为第一页
  fetchListGroup({
    page: pageNumber.value,
    size: pageSize.value,
    name: queryForm.name
  })
}

const handleCurrentChange = (page: number) => {
  pageNumber.value = page
  fetchListGroup({
    page: pageNumber.value,
    size: pageSize.value,
    name: queryForm.name
  })
}
</script>
  
  <style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  margin-top: 25px; /* 添加顶部间距 */
}
.demo-form-inline {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}
</style>
  
  